package top.byteio.common.mq.handler;

import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import top.byteio.common.cache.lock.DistributedLock;
import top.byteio.common.core.constants.MqConstants;
import top.byteio.common.core.utils.StringUtils;
import top.byteio.common.mq.pojo.dto.MqDTO;
import top.byteio.common.mq.pojo.dto.MqResultDTO;

import java.util.concurrent.TimeUnit;

/**
 * RabbitMq消息生产和消费处理器
 * @author lerryxia
 **/
@RequiredArgsConstructor
public class RabbitMqProducerSender implements MqProducerSender {

    private final DistributedLock distributedLock;

    private final RabbitTemplate rabbitTemplate;


    /**
     * 发送MQ消息
     * @param mqDto 消息体
     * @return 结果
     */
    @Override
    public <T> MqResultDTO sendMq(MqDTO<T> mqDto) {
        MqResultDTO resultDto = new MqResultDTO();
        String key = StringUtils.format(MqConstants.LOCK_KEY, mqDto.getTopic() + "_" + mqDto.getPriKey());
        try {
            //获取分布式锁
            if (distributedLock.tryLock(key,MqConstants.LOCK_TIMEOUT, TimeUnit.SECONDS)) {
                //发送MQ消息
                rabbitTemplate.convertAndSend(mqDto.getExchange(),mqDto.getRoutingKey(),JSON.toJSONString(mqDto));
                resultDto.setResult(Boolean.TRUE);
            }
        } catch (Exception e) {
            resultDto.setResult(Boolean.FALSE);
            resultDto.setErrorMsq(e.getMessage());
        }
        //释放分布式锁
        distributedLock.unLock(key);
        return resultDto;
    }
}
